package com.example.fanpaiyouxi

class CardGameModel {

    val cards: Array<Card> = Array(16) { Card(0) }
    private var firstFlippedIndex: Int? = null
    private var secondFlippedIndex: Int? = null
    private var canFlip = true

    init {
        initializeCards()
    }

    private fun initializeCards() {
        val values = (1..8).flatMap { listOf(it, it) }.shuffled()
        for (i in cards.indices) {
            cards[i] = Card(values[i])
        }
    }

    fun flipCard(position: Int): FlipResult {
        if (!canFlip || cards[position].isFaceUp || cards[position].isMatched) {
            return FlipResult.NoChange
        }

        cards[position].isFaceUp = true

        return when {
            firstFlippedIndex == null -> {
                firstFlippedIndex = position
                FlipResult.FirstCard
            }
            secondFlippedIndex == null -> {
                secondFlippedIndex = position
                val firstCard = cards[firstFlippedIndex!!]
                val secondCard = cards[secondFlippedIndex!!]

                if (firstCard.value == secondCard.value) {
                    firstCard.isMatched = true
                    secondCard.isMatched = true
                    firstFlippedIndex = null
                    secondFlippedIndex = null
                    FlipResult.Match
                } else {
                    canFlip = false
                    FlipResult.Mismatch(firstFlippedIndex!!, secondFlippedIndex!!)
                }
            }
            else -> {
                FlipResult.NoChange
            }
        }
    }

    fun resetFlippedCards() {
        firstFlippedIndex?.let { cards[it].isFaceUp = false }
        secondFlippedIndex?.let { cards[it].isFaceUp = false }
        firstFlippedIndex = null
        secondFlippedIndex = null
        canFlip = true
    }

    fun isCardMatched(position: Int): Boolean {
        return cards[position].isMatched
    }

    fun isGameComplete(): Boolean {
        return cards.all { it.isMatched }
    }

    sealed class FlipResult {
        object FirstCard : FlipResult()
        object Match : FlipResult()
        object NoChange : FlipResult()
        data class Mismatch(val firstIndex: Int, val secondIndex: Int) : FlipResult()
    }
}

data class Card(
    val value: Int,
    var isFaceUp: Boolean = false,
    var isMatched: Boolean = false
)